package cc.rengu.igas.smps.core.packswitch;

import cc.rengu.igas.smps.common.enums.RespCodeEnum;
import cc.rengu.jradp.packetswitch.IncomingPackSwitchImpl;
import cc.rengu.jradp.packetswitch.OutgoingPackSwitchImpl;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.utility.util.MD5Util;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

/**
 * 与意锐服务商音箱通讯
 *
 * @author WKF
 */
public class InspiryVoiceClientPackSwitch implements IncomingPackSwitchImpl, OutgoingPackSwitchImpl {

    @Override
    public int beforeOutgoPackSwitch() throws Exception {

        return 0;
    }

    @Override
    public byte[] afterOutgoPackSwitch(byte[] arg0) throws Exception {
        RgLogger rglog = RgLog.getLogger(this.getClass().getName());
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        xmlTreeUtil.setXmlTreeStringValue("_MESSAGEHEAD/http/Content-Type", "application/json;charset=utf-8");
        xmlTreeUtil.setXmlTreeStringValue("_MESSAGEHEAD/http/ArgList", "Content-Type");
        String jsonBefore = new String(arg0);
        /* 生成签名 */
        String sign = generateSignBlockString(jsonBefore);
        if (null == sign) {
            rglog.error("生成加签Block失败!");
            throw new BizException(RespCodeEnum.GENERATE_SIGN_BLOCK_ERROR.getRespCode(), RespCodeEnum.GENERATE_SIGN_BLOCK_ERROR.getRespDesc());
        }
        rglog.debug("签名:<{}>", sign);
        /**添加sign字符串到报文中*/
        String jsonAfter = jsonStringAppendSign(jsonBefore, sign);

        return jsonAfter.getBytes();
    }


    @Override
    public int afterInComPackSwitch() {

        return 0;
    }

    @Override
    public byte[] beforeInComPackSwitch(byte[] arg0) throws Exception {
        RgLogger rglog = RgLog.getLogger(this.getClass().getName());
        //不验签了
        return arg0;
    }

    private String generateSignBlockString(String jsonString) {
        RgLogger rglog = RgLog.getLogger(this.getClass().getName());
        try {
            if (null != jsonString && 0 != jsonString.trim().length()) {
                Map maps = (Map) JSON.parse(jsonString);
                ArrayList<String> arrayList = new ArrayList<>();
                int i = 0;
                Object key;
                Object value;
                for (Object map : maps.entrySet()) {
                    key = ((Map.Entry) map).getKey();
                    value = ((Map.Entry) map).getValue();
                    if (!"sign".equals(key) && null != value) {
                        if (!"signMethod".equals(key)) {
                            if (!"key".equals(key)) {
                                arrayList.add(key + "=" + value + "&");
                            }
                        }
                    }
                    i++;
                }
                String[] strArray = arrayList.toArray(new String[arrayList.size()]);
                Arrays.sort(strArray);
                StringBuffer stringBuffer = new StringBuffer();
                for (i = 0; i < strArray.length; i++) {
                    stringBuffer.append(strArray[i]);
                }
                stringBuffer.append("key=" + maps.get("key") + "&");
                return MD5Util.MD5Encode(stringBuffer.substring(0, stringBuffer.length() - 1).toString()).toUpperCase();
            }
        } catch (Exception e) {
            rglog.error("生成sign签名失败");
            rglog.error("系统异常!");
            return null;
        }
        return null;
    }

    private String jsonStringAppendSign(String jsonString, String sign) {
        RgLogger rglog = RgLog.getLogger(this.getClass().getName());
        try {
            if (null != jsonString && 0 != jsonString.trim().length()) {
                Map maps = (Map) JSON.parse(jsonString);
                maps.put("sign", sign);
                if (maps.get("key") != null) {
                    maps.remove("key");
                }
                return JSON.toJSONString(maps);
            }
        } catch (Exception e) {
            rglog.error("添加sign签名失败");
            rglog.error("系统异常!");
            return null;
        }
        return null;
    }


}
